package Network.UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;


public class EchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public EchoClient(String serverIp, int serverPort) throws IOException {  
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }   

    //启动客户端,发送数据,接收数据,关闭连接
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("客户端启动！");
        while(true) {
            //1.从控制台读取要发送的数据内容(用字符串表示)
            System.out.print(">");
            String request = scanner.nextLine(); 
            //2.构造成UDP请求，并发送.不光要填内容，还要填服务器的地址和端口号
            DatagramPacket reqPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                                            InetAddress.getByName(serverIp),serverPort); 
            socket.send(reqPacket);
            //3.接收服务器响应的数据
            DatagramPacket resPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(resPacket);
            String response = new String(resPacket.getData(),0,resPacket.getLength());
            //4.把响应的数据解析并打印
            System.out.println(response);
        }
    }
    public static void main(String[] args) throws IOException {
        EchoClient echoclient = new EchoClient("127.0.0.1",9090);
        echoclient.start();
    }
}
